from QQLoginTool.QQtool import OAuthQQ
from django.conf import settings
from django.shortcuts import render

# Create your views here.
from rest_framework.response import Response

from rest_framework.views import APIView
from rest_framework_jwt.settings import api_settings

from oauth.models import OAuthQQUser
from oauth.serializers import QQUserSerializer
from oauth.utils import generate_encrypted_openid


class QQURLView(APIView):
    """
   提供QQ登录页面网址
   """
    def get(self, request):
        # next表示登录成功后要进入的界面
        next = request.query_params.get('next')
        if not next:
            next = '/'

        # 通过第三方包QQLoginTool: 生成QQ登录界面的url地址
        oauth = OAuthQQ(settings.QQ_CLIENT_ID,
                        settings.QQ_CLIENT_SECRET,
                        settings.QQ_REDIRECT_URI,
                        state=next)
        login_url = oauth.get_qq_url()
        # 返回QQ登录界面的url地址
        return Response({'login_url': login_url})


class QQUserView(APIView):
    """QQ认证接口"""
    """用户扫码登录的回调处理"""
    def get(self, request):
        """提取code请求参数"""
        # 获取code参数
        code = request.query_params.get('code')
        # 校验code参数
        if not code:
            return Response({'message': '缺少code'})

        oauth = OAuthQQ(settings.QQ_CLIENT_ID,
                        settings.QQ_CLIENT_SECRET,
                        settings.QQ_REDIRECT_URI,
                        state=next)  # state参数可以不传, 因为在当前接口使用不到

        try:
            # 使用code向QQ服务器请求access_token
            access_token = oauth.get_access_token(code)
            # 使用access_token向QQ服务器请求openid
            openid = oauth.get_open_id(access_token)
        except:
            return Response({'message': 'QQ服务器异常'})

        # 根据openid，从映射表中查询绑定的美多用户对象
        try:
            qquser = OAuthQQUser.objects.get(openid=openid)
        except:
            # 如果openid没绑定美多商城用户，则需要进行绑定，
            # 在这里将openid返回给前端，绑定时再传递服务器
            # 查询不到美多用户，说明是第一次使用QQ登录，则返回openid, 等待后续用户的绑定操作
            openid = generate_encrypted_openid(openid)
            return Response({'openid': openid})
        else:
            # 能查询到美多用户，则生成并响应：jwt，user_id, username，完成QQ登录流程
            # 到此表示登录成功，如果openid已绑定美多商城用户，直接生成JWT token，并返回
            jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
            jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
            # 获取qquser关联的user
            user = qquser.user
            payload = jwt_payload_handler(user)
            token = jwt_encode_handler(payload)

            context = {
                'token': token,
                'user_id': user.id,
                'username': user.username
            }

            return Response(context)

    def post(self, request):
        """绑定openid和美多用户"""
        # 创建序列化器对象
        serializer = QQUserSerializer(data=request.data)
        # 校验请求参数
        serializer.is_valid(raise_exception=True)
        # 绑定openid和美多用户（添加一条表数据）
        user = serializer.save()
        # 到此步为止，绑定成功，生成JWT并响应，完成登录
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)

        context = {
            'token': token,
            'user_id': user.id,
            'username': user.username
        }

        return Response(context)
